<template>
  <div class="div-container">
    <div class="tabs">
      <div class="tab-item" :class="{ active: usePwd }" @click="changeLoginType('account')">
        {{ $t('user.login.tab-login-credentials') }}
      </div>
      <div class="tab-item" :class="{ active: !usePwd }" @click="changeLoginType('phone')">
        {{ $t('user.login.tab-login-mobile') }}
      </div>
    </div>
    <a-form
      id="formLogin"
      class="user-layout-login"
      ref="formLogin"
      :form="form"
      @submit="handleSubmit"
    >
      <template v-if="usePwd">
        <a-form-item>
          <a-input
            size="large"
            type="text"
            :placeholder="$t('all.autotext1190')"
            v-decorator="[
              'username',
              { rules: [{ required: true, message: $t('all.autotext1190') }], validateTrigger: 'change' },
            ]"
          >
            <a-icon slot="prefix" type="user" :style="{ color: '#D6DFEC' }" />
          </a-input>
        </a-form-item>

        <a-form-item style="margin:0;">
          <a-input-password
            size="large"
            :placeholder="$t('all.autotext575')"
            v-decorator="['pwd', { rules: [{ required: true, message: $t('all.autotext575') }], validateTrigger: 'blur' }]"
          >
            <a-icon slot="prefix" type="lock" :style="{ color: '#D6DFEC' }" />
          </a-input-password>
        </a-form-item>
      </template>
      <template v-else>
        <a-form-item>
          <a-input-group compact>
            <a-select default-value="86" size="large" style="width:80px">
              <a-select-option value="86">
                +86
              </a-select-option>
            </a-select>
            <a-input
              :placeholder="$t('all.autotext396')"
              v-decorator="[
                'phone',
                { rules: [{ required: true, message: $t('all.autotext396') },{ pattern: /^(?:(?:\+|00)86)?1[3-9]\d{9}$/, message: $t('all.autotext140') }], validateTrigger: 'change' },
              ]"
              size="large"
              style="width:calc(100% - 80px)"
            />
          </a-input-group>
        </a-form-item>
        <a-form-item style="margin:0;">
          <a-row :gutter="8">
            <a-col :span="15">
              <a-input
                v-decorator="[
                  'code',
                  { rules: [{ required: true, message: $t('all.autotext639') }] },
                ]"
                size="large"
                :placeholder="$t('all.autotext639')"
              />
            </a-col>
            <a-col :span="9" style="text-align: right;">
              <a-button
                size="large"
                type="primary"
                ghost
                @click="getCode"
                :disabled="codeBtnDisabled"
              >
                {{ codeBtnDisabled?`${seconds}${$t('all.autotext1161')}`:$t('all.autotext1151') }}
              </a-button>
            </a-col>
          </a-row>
        </a-form-item>
      </template>
      <!-- <div style="margin:5px 0;white-space: nowrap">
        <span @click="changeLoginType"
              :style="{color:'#1890ff',cursor:'pointer',margin:'5px 0'}"
        >{{ usePwd? $t('all.autotext805.1') : $t('all.autotext805.2') }}</span>
      </div> -->
      <a-form-item class="agree">
        <a-checkbox @change="onChange" :checked="check">
          {{ $t('all.autotext1438.1') }}<a :href="privacyUrl" target="_blank">《{{ $t('all.autotext85') }}》</a>
        </a-checkbox>
      </a-form-item>
      <a-form-item>
        <a-form-item style="margin-top: 10px">
          <a-button
            size="large"
            type="primary"
            htmlType="submit"
            class="login-button"
            :loading="state.loginBtn"
            :disabled="state.loginBtn"
          >
            {{ $t('all.autotext1154') }}
          </a-button>
        </a-form-item>
        <div class="forget">
          <div class="forget-btn" @click="changePassword">{{ $t('user.login.forgot-password') }}</div>
        </div>
      </a-form-item>
    </a-form>
    <UpdatePwdModal :modalVisible="updatePwdModalVisible" @cancel="updatePwdModalVisible = false"></UpdatePwdModal>
  </div>
</template>

<script>
import { mapActions } from 'vuex'
import { timeFix } from '@/utils/util'
import { firtSign, apiValidPwdExpiration, sendCode, userRecentlyPro, infoPm } from '@api/login'
import { getProjectList } from '@/api/overview/contract'
import UpdatePwdModal from '@comp/GlobalHeader/UpdatePwdModal.vue'
import { ACCESS_TOKEN, ACCESS_TOKEN_TEMP } from '@/store/mutation-types'
import storage from 'store'


export default {
  components: {
    UpdatePwdModal
  },
  data () {
    return {
      check: false,
      privacyUrl: location.origin + '/privacy',
      form: this.$form.createForm(this),
      state: {
        loginBtn: false
      },
      updatePwdModalVisible: false,
      usePwd: true, // 使用密码登录
      seconds: 60, // 倒计时
      timer: null, // 定时器
      codeBtnDisabled: false // 获取验证码按钮是否禁用
    }
  },
  created () {
    this.fetFirstSign()
  },
  methods: {
    async fetFirstSign () {
      const ifFirstSign = await firtSign()
      this.check = !ifFirstSign
    },
    changePassword () {
      this.$parent.isForget = true
    },
    ...mapActions(['Login', 'ClearProject', 'getNoTodoCounts','getNoReadCounts']),
    onChange (e) {
      this.check = e.target.checked
    },
    // handler
    handleSubmit (e) {
      e.preventDefault()
      const {
        form: { validateFields },
        state,
        Login
      } = this

      const validateFieldsKey = ['username', 'pwd', 'phone', 'code']

      validateFields(validateFieldsKey, { force: true }, (err, values) => {
        if (!err) {
          if (!this.check) {
            this.$message.error(this.$t('all.autotext1526'))
            return
          }
          state.loginBtn = true
          const loginParams = {}
          if (this.usePwd) {
            loginParams.account = values.username
            loginParams.pwd = values.pwd
          } else {
            loginParams.account = values.phone
            loginParams.code = values.code
          }

          this.$store.dispatch('ClearProject').then(() => {
            Login(loginParams)
              .then(res => this.loginSuccess(res))
              .finally(() => {
                state.loginBtn = false
              })
          })
        } else {
          setTimeout(() => {
            state.loginBtn = false
          }, 600)
        }
      })
    },
    async loginSuccess (res) {
      const info = await userRecentlyPro({})
      const isPm = await infoPm()
      const list = await getProjectList({
        pageNumber: 1,
        pageSize: 10000
      })
      this.getNoTodoCounts({})

      this.getNoReadCounts({})

      // 注释部分为环境切换
      // const list = await getAllProGroupByType({})
      // localStorage.setItem('CURRENT_ENV', '') // 清空环境缓存
      localStorage.setItem('CURRENT_ROLECODE', info.roleCode)
      if (['SYS_ADMIN', 'PROJECT_ADMIN', 'SYS_FINANCE', 'SYS_BIZ'].includes(info.roleCode)) {
        this.toJump(res)
      } else {
        localStorage.setItem('CURRENT_PROJECT_LIST', JSON.stringify(list.page.content))
        // const record = list[Object.keys(list)[0]][0]
        // this.$store.dispatch('EnterProject', list[Object.keys(list)[0]][0]).then(e => {
        //   this.toJump(res, record)
        // })
        const record = info.proInfo || list.page.content[0]
        this.$store.dispatch('EnterProject', record).then(e => {
          this.toJump(res, record, isPm)
        })
      }
    },
    async toJump (res, record, isPm) {
      // 没有认证的情况下跳去认证页
      // res[verified_status] == 0  跳转到 实名
      // if (res['isAdmin'] === 0 && res['verified_status'] === 0) {
      //   this.$router.push({ path: '/person' })
      // } else
      if (res.isRestPwd === 0) {
        // 系统用户 且未重置密码
        return this.$router.push({ path: '/person', query: { type: 1 } })
      }

      const valid = await this.validPwdExpiration()
      if (!valid) return

      if (record) {
        if (isPm) {
          // this.$router.push({ path: '/site' })
          this.$router.push({ path: '/overview/all' })
        } else {
          this.$router.push({ path: '/high' })
        }
      } else {
        this.$router.push({ path: '/overview/all' })
      }

      // 延迟 1 秒显示欢迎信息
      setTimeout(() => {
        this.$notification.success({
          message: this.$t('all.autotext408'),
          description: `${timeFix()}，${this.$t('all.autotext1198')}`
        })
      }, 1000)
    },
    validPwdExpiration () {
      return new Promise(async resolve => {
        const res = await apiValidPwdExpiration()
        const { leftDate, needRemind } = res
        if (needRemind) {
          if (+leftDate <= 0) {
            this.$router.push({ path: '/person', query: { type: '2' } })
            return resolve(false)
          }
          if (+leftDate <= 3) {
            this.$confirm({
              title: this.$t('all.autotext730'),
              icon: () => {},
              content: `${this.$t('all.autotext137.1')}${leftDate}${this.$t('all.autotext137.2')}`,
              cancelText: this.$t('all.autotext93'),
              okText: this.$t('all.autotext217'),
              onOk: () => {
                resolve(false)
                this.updatePwdModalVisible = true
                this.preventRouteByUrl()
              },
              onCancel: () => {
                resolve(true)
              }
            })
          }
        } else {
          resolve(true)
        }
      })
    },
    preventRouteByUrl () {
      storage.set(ACCESS_TOKEN_TEMP, storage.get(ACCESS_TOKEN))
      this.$store.dispatch('Logout')
    },
    changeLoginType () {
      this.usePwd = !this.usePwd
    },
    async getCode () {
      if (this.codeBtnDisabled) return
      const {
        form: { validateFields }
      } = this

      const validateFieldsKey = ['phone']
      validateFields(validateFieldsKey, { force: true }, async (err, values) => {
        if (err) return
        await sendCode({ phone: this.form.getFieldValue('phone') })
        this.$message.success(this.$t('all.autotext1475'))
        this.codeBtnDisabled = true
        this.timer = setInterval(() => {
          this.seconds--
          if (this.seconds <= 0) {
            clearInterval(this.timer)
            this.seconds = 60
            this.codeBtnDisabled = false
          }
        }, 1000)
      })
    }
  }
}
</script>

<style lang="less" scoped>
.div-container{
  display: flex;
  flex-direction: column;
  align-items: center;
}
.user-layout-login {
  width: 325px;
  ::v-deep .ant-input-suffix {
    color: #ABB8CE;
  }
  /* 去除谷歌浏览器中input自动填充背景 */
  ::v-deep input {
    box-shadow: 0 0 0 1000px #fff inset;
  }

  button.login-button {
    padding: 0 15px;
    font-size: 16px;
    height: 40px;
    width: 100%;
    background-color: #3D92FF;
    border: none;
  }

  .forget {
    font-size: 14px;
    color: #ABB8CE;
    text-align: center;
    position: relative;

    &:after {
      content: '';
      display: block;
      border-top: 1px solid #E5EBF3;
      width: 100%;
      height: 0;
      position: absolute;
      top: 50%;
      left: 0;
      z-index: 3;
    }

    .forget-btn {
      position: relative;
      display: inline-block;
      background: #fff;
      padding: 0 13px;
      z-index: 4;
      cursor: pointer;
    }
  }
  .agree {
    margin: 10px 0 0 0;
    white-space: nowrap;
    span {
      color: #3D92FF;
    }
  }
}

.tabs {
  display: flex;
  justify-content: center;
  // gap:36px;
  margin: 40px 0;
  .tab-item {
    text-align: center;
    font-size: 14px;
    // color: #000000;
    color: #687991;
    cursor: pointer;
    width: 120px;
    padding-bottom: 10px;
    border-bottom: 1px solid rgba(240, 240, 240, 1);
    &.active {
      color: var(--primary-color);
      border-bottom: 2px solid  var(--primary-color);
    }
  }
}
</style>
